package com.k2data.k2app.common;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.k2data.k2app.exception.K2ResponseException;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Component
public class MyConstant {
    public static final int USEFUL=0;
    public static final int UNUSEFUL=1;
    public static final int YES_INTEGER=1;
    public static final int SUCCESS=1;
    public static final int FAILED=2;
    public static final String RESULT_TYPE_WARNING="warning";
    public static final String RESULT_TYPE_STATISTICAL="statistical";
    public static final String RESULT_TYPE_RULES="rules";

    public static final String DEVICE_STATUS_OUTLINE="不在线";
    public static final String DEVICE_STATUS_OUTLINE_EN="outline";
    public static final String DEVICE_STATUS_STOP="停机";
    public static final String DEVICE_STATUS_STOP_EN="stop";
    public static final String DEVICE_STATUS_HEALTH="健康";
    public static final String DEVICE_STATUS_HEALTH_EN="health";
    public static final String DEVICE_STATUS_SUB_HEALTH="亚健康";
    public static final String DEVICE_STATUS_SUB_HEALTH_EN="subHealth";
    public static final String DEVICE_STATUS_EARLY_WARNING="预警";
    public static final String DEVICE_STATUS_EARLY_WARNING_EN="warning";
    /**
     * 多少时间段内重复预警不处理
     */
    public static final Long FILTER_TIME = 30L;
    /**
     * the status of one job in a task
     */
    public static final int RUNNING = 0;
    /**
     * Attribute【group_name】 of the job in timing task
     */
    public static final String JOB_GROUP_NAME = "K2ASSET_JOBGROUP_NAME";
    /**
     * Attribute【group_name】 of the trigger in timing task
     */
    public static final String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";
    /**
     * 预警类型
     * <p>
     *     mq:站内消息
     *     sms:短信
     *     sms:邮箱
     */
    public static final String WARING_TYPE_MQ = "mq";
    public static final String WARING_TYPE_SMS = "sms";
    public static final String WARING_TYPE_MAIL = "mail";

    /**
     * the string value of a level
     * <p>1: 亚健康
     * <p>2: 预警
    */
    public static String getStatus(Integer level){
        if (level==1) {
            return DEVICE_STATUS_SUB_HEALTH;
        } else if (level==2){
            return DEVICE_STATUS_EARLY_WARNING;
        }
        return "level不是１or 2,未定义健康状态!";
    }
    public static Map<String,String> deviceStatus = Maps.newConcurrentMap();


    @Getter
    @Value("${pas.sso.service}")
    private String tokenService;

    @Value("${pas.sso.token}")
    @Getter
    private String tokenValue;

    @Getter
    @Value("${pas.proxy.service}")
    private String service;

    @Value("${pas.proxy.owner}")
    @Getter
    String owner;

    @Value("${pas.proxy.creator}")
    @Getter
    String creator;

    @Value("${pas.proxy.mqSuffix}")
    @Getter
    String mqSuffix;

    @Getter
    @Value("${kmx.postData.url}")
    private String postdataUrl;

    @Getter
    @Value("${kmx.fieldGroups.url}")
    private String fieldGroupsUrl;
    /**
     * 查询fileldGroup名称规则，1表示在表名称前面加前缀 2表示不加前缀  kmx.fieldGroup.rule.before表示前缀名称
     */
    @Getter
    @Value("${kmx.fieldGroupId.rule}")
    private String groupIdRule;

    @Getter
    @Value("${kmx.fieldGroupId.name}")
    private String groupIdName;

    /**
     * 设备停机检测定时时间，默认10分钟
     */
    @Getter
    @Value("${schedule.device.status.cron}")
    private String cron;

    /**
     * 设备停机检测时间，默认1小时
     */
    @Getter
    @Value("${schedule.device.status.overdue}")
    private String overdue;

    @Getter
    @Value("${schedule.device.status.overdueOutline}")
    private String overdueOutline;


    public String proLoginUrl(){
        return getService()+"projects?owner="+getOwner();
    }

    /**
     * 拼接带token的url，用于请求pas平台的cas服务
     * @param url
     * @return
     */
    public String getURI(String url) throws K2ResponseException {
        try {
            url = URLEncoder.encode(url,"UTF-8");
            url = getTokenService()+"?service="+url+"&token="+getTokenValue();
            return url;
        } catch (UnsupportedEncodingException e) {
            throw new K2ResponseException(ResponseConstant.URL_PARSE_ERROR_VALUE,
                    String.format("%s", ResponseConstant.URL_PARSE_ERROR));
        }
    }

    /**
     * 拼接查询条件,返回&链接的字符串
     *
     * @param params
     * @return
     */
    public String getQueryCondition(Map<String,Object> params){
        StringBuffer sb = new StringBuffer();
        params.forEach((k,v) -> {
            if(v !=null && !"".equals(v.toString())){
                if(!"".equals(sb.toString())){
                    sb.append("&");
                }
                sb.append(k).append("=").append(v.toString());
            }
        });
        return sb.toString();
    }

    public String getFieldGroup(String nameEn){
        // tcs 特殊处理
        if (nameEn.startsWith("tcs")) {
            if(getGroupIdRule() == null || getGroupIdRule().equals("2")){
                String a = Joiner.on("_").join(Splitter.on('_')
                        .trimResults()
                        .omitEmptyStrings()
                        .splitToList(nameEn).subList(0, 2));
                return a;
            }else{
                String a = Joiner.on("_").join(Splitter.on('_')
                        .trimResults()
                        .omitEmptyStrings()
                        .splitToList(nameEn).subList(0, 2));
                return getGroupIdName()+"_"+a;
            }

        }
        else{
            return nameEn;
        }
    }
}
